from rest_framework import permissions

from artmarket.models import Artwork


class IsArtistOrReadOnly(permissions.BasePermission):
    """
    艺术品的列表查看允许任何人查看, 但是创建需要是艺术家, 修改和删除需要是艺术家并且是修改自己的作品
    """

    def has_permission(self, request, view):
        if request.method == 'GET':
            return True
        elif request.method == 'POST':
            return request.user.role == 0

        elif request.method in ['PUT', 'DELETE']:
            user = request.user
            artwork_id = view.kwargs.get('pk')  # 获取要修改的作品的ID
            try:
                artwork = Artwork.objects.get(pk=artwork_id)
                # 检查用户是艺术家并且是修改自己的作品
                return user.role == 0 and artwork.artist == user
            except Artwork.DoesNotExist:
                return False

        return False
